{% extends "base.html" %}


{% block head %}
    <script type="application/javascript" src="{{url_for('static',filename='jquery.ztree.core-3.5.min.js')}}"></script>
    <script type="application/javascript" src="{{url_for('static',filename='jquery.ztree.excheck-3.5.min.js')}}"></script>
    <link href="{{url_for('static',filename='zTreeStyle.css')}}" rel="stylesheet">
   <style type="text/css">
   .info-content {
          position: relative;
          background-color: #BDE5F8;
          border: 1px solid #999999;
          border: 1px solid rgba(0, 0, 0, 0.2);
          border-radius: 6px;
          outline: none;
          -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
                  box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
          background-clip: padding-box;
      }
   .error-content {
          position: relative;
          background-color: #FFBABA;
          border: 1px solid #999999;
          border: 1px solid rgba(0, 0, 0, 0.2);
          border-radius: 6px;
          outline: none;
          -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
                  box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
          background-clip: padding-box;
      }
    .myleft {
        float:left;
        width:25%;
        height: 100%;
    }
    .myright {
        float:right;
        width:75%;
        height: 100%;
    }
    .clear {
        clear:both;
    }
   ul.ztree {border: 1px solid #617775;width:220px;height:360px;overflow-y:scroll;overflow-x:auto;}
   table,tr,th .above-ztree {border: 1px solid #617775;width:220px; background: #eeeeee;overflow-x:auto;}
   h1, h2, h3, h4, h5, h6 {color: #2f332a;font-weight: bold;font-family: Helvetica, Arial, sans-serif;padding-bottom: 5px;}
   h1 {font-size: 24px;line-height: 34px;text-align: center;}
    </style>

{% endblock %}
{% block body%}

    <SCRIPT type="text/javascript">
		<!--
		var setting = {
			view: {
				selectedMulti: false
			},
			check: {
				enable: true
			},
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				onCheck: onCheck
			}
		};

        var counter=0;  //counter for "one by one command"
        var post_hostid= new Array()

		var zNodes =[
            {% for cluster in clusters %}
			{ id : {{ cluster.clusterid }} ,pId:0, name:"{{ cluster.clustername }}",open:true },
            {% endfor %}
            {% for host in hosts %}
			{ id : "{{ host.clusterid }}.{{ host.hostid }}" ,pId:{{ host.clusterid }}, name:"{{ host.host_ip }}",icon:"{{url_for('static',filename='server.jpg')}}",},
            {% endfor %}
		];

		var clearFlag = false;
		function onCheck(e, treeId, treeNode) {
			count();
			if (clearFlag) {
				clearCheckedOldNodes();
			}
		}

        function get_finished_count(){
            var result_url="/progress_bar/".concat("command_count_",command_token)
            if  ( $('#percentage_Modal').css("display") != "block" ){
                   window.clearInterval(interval_id)
            }
            $.ajax({
                url:result_url,
                type:"GET",
                timeout:290,
                datatype:"html",
                success:function(data,status){
            console.log(data)
            var count_json=JSON.parse(data)
            var count=count_json.finished_count
            if (count== null && $('#finished_count').css("width") =="1%"){
                count=0;
            }
            else if(count== null ){
                return;
            }
            var pt=parseInt(count*100/post_hostid.length)
            if ( pt==0  ){
                pt=1;
            }
            var percentage=pt.toString().concat("%")
            $('#finished_count').css("width",percentage)
            $('#display_count').text(percentage.concat(" Complete"))
            $('#display_count_text').text("Total :  ".concat(post_hostid.length,"  Completed : ",count))
//            console.log(percentage);
            }
            })
        }

		function clearCheckedOldNodes() {
			var zTree = $.fn.zTree.getZTreeObj("hosttree"),
			nodes = zTree.getChangeCheckedNodes();
			for (var i=0, l=nodes.length; i<l; i++) {
				nodes[i].checkedOld = nodes[i].checked;
			}
		}
        function list_to_text(mylist) {
            str="</br>";
            for (i in mylist.sort()) {
                str=str+'<button type="button" class="btn btn-info btn-sm ">'+mylist.sort()[i]+'</button>'
            }
            return str;
        }
		function count() {
			var zTree = $.fn.zTree.getZTreeObj("hosttree");
			checkCount = zTree.getCheckedNodes(true).length;
			nocheckCount = zTree.getCheckedNodes(false).length;
			changeCount = zTree.getChangeCheckedNodes().length;
            var checked_hosts=zTree.getCheckedNodes(true);
            var checked_hostip= new Array();
            var checked_hostid = new Array();
            for (i in checked_hosts){
                tmp="#"+checked_hosts[i].tId+"_a";
                host_ip=$(tmp).attr("title");
                tmp2="#"+$(tmp).parent().parent().attr("id").replace(/_ul$/,"_a");
                clustername=$(tmp2).attr("title");
                for (var x in zNodes ){
                    if (zNodes[x].name == clustername && zNodes[x].pId == "0"  ){
                        var clusterid= zNodes[x].id;
                        break;
                    }
                }
                for (var y in zNodes){
                    if (zNodes[y].name == host_ip && zNodes[y].pId == clusterid ){
{#                        alert(zNodes[y].id)#}
                        var tmp_hostid = zNodes[y].id;
                        var reg = /^(\d+\.)/;
{#                        alert(tmp_hostid)#}
                        hostid=tmp_hostid.replace(reg,"");
                    }
                }
                if ($(tmp).attr("class").match("level0") ==  null){
                    checked_hostip.push($(tmp).attr("title"));
                    checked_hostid.push(hostid);
                }

            }
            $("#checked_hosts").html(list_to_text(checked_hostip));
            post_hostid= checked_hostid
            $("#checked_hosts_count").text(checked_hostip.length);
		}
		function createTree() {
			$.fn.zTree.init($("#hosttree"), setting, zNodes);
            var zTree = $.fn.zTree.getZTreeObj("hosttree");
            zTree.expandAll(false)
			count();
			clearFlag = $("#last").attr("checked");
		}

		$(document).ready(function(){
			createTree();
			$("#init").bind("change", createTree);
			$("#last").bind("change", createTree);
            $('#percentage_Modal').on('shown.bs.modal', function () {
            interval_id = window.setInterval('get_finished_count()',300)
                })
            $('#one_by_one').on('hidden.bs.modal', function () {
            counter=0;
            $('#finished_count').css("width","%1");
            $('#display_count_text').text("")
                })
		});
		//-->
        function addnew_panel(panel_count){
            var new_panel_count = panel_count+1 ;
            $('.collapse').collapse();
            var txt='<div class="panel panel-default" id="panel'+new_panel_count+'"> \
            <div class="panel-heading">   \
            <h4 class="panel-title">      \
            <a data-toggle="collapse" data-toggle="collapse" data-parent="#accordion" href="#collapse'+new_panel_count+'" id="panel-title'+new_panel_count+'"> \
            Command Result will display below:  \
            </a>  \
            </h4>  \
            </div>   \
            <div id="collapse'+new_panel_count+'" class="panel-collapse collapse in"> \
            <div class="panel-body" id="panel-body'+new_panel_count+'"> \
            Display here.  \
            </div>  \
            </div>  \
             </div>';
            $("#panel"+panel_count).after(txt);
        }
        function s10(){
            var data=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
            var result="";
            for(var i=0;i<10;i++){
                var r=Math.floor(Math.random()*52);
                result+=data[r];
            }
            return result
        }

        function post_one_to_server(){
            var startDate= new Date()
            var datestring=startDate.getTime().toString()
            if (counter == 0){
                first_time=startDate;
            }
            if (counter>=post_hostid.length){
                $('#one_by_one').modal('hide');
                return false;
            }
            command_token=datestring.concat('_',s10())
            var total_panel_counter = 1
            check_number=/^\d+$/;
            timeout=$.trim($("#timeout").val())
            if(!check_number.test(timeout)){
                alert("timeout must be a number")
                return false
            }
            if($.trim($("#command").val())==""){
                alert("please give me the command!")
                return false
            }
            if(post_hostid.length == 0){
                alert("please select the hosts !")
                return false
            }
            var panel_count=$(".panel-default").size()
            if (counter == 0){
                if($.trim($("#panel-body1").text()) != "Display here.") {
                addnew_panel(panel_count);
                total_panel_counter=panel_count+1
                }
            }
            else{
                total_panel_counter=panel_count
            }

            $('#one_by_one').modal('show');
            $('#one_by_one_title').text("Please wait...")
            $('#next_host').text("Next host");
            $('#one_by_one_result').html("result of </br>".concat($.trim($("#command").val()),"</br>will display here"))
            $.ajax({
                        url: "/command",
                        type: 'POST',
                        data:{
                        csrf_token:"{{ csrf_token() }}",
                        runuser:$('input[name="runuser"]:checked').val(),
                        command: $.trim($("#command").val()),
                        checked_hostid:post_hostid[counter],
                        timeout:timeout,
                        command_token:command_token
                        },
                        dataType:"html",
                        timeout:0,
                        statusCode: {
                        500: function() {
                            $('#one_by_one').modal('hide');
                        alert( "Sorry , something is wrong with octopus" );
                        },
                        400: function() {
                            $('#one_by_one').modal('hide');
                        alert( "Sorry , CSRF token expired or missing,please refresh this page" );
                        }
                        },
//                        error:function(jqXHR,textStatus,errorThrown){
//                            $('#percentage_Modal').modal('hide');
//                            alert(errorThrown);
//                        },
                        success:function(data,status){
                        content=data;
                        var endDate=new Date();
                        tmp_json=JSON.parse(content)
                        counter+=1;
                        result_string=""
                        for (var i=0;i< tmp_json.length;i++){
                        result_string=result_string+tmp_json[i][0]+"</br>"+tmp_json[i][1]+"<br>"
                        result_string=result_string.replace(/\r\n/g,"<br>")
                        }
                    $("#panel-title"+total_panel_counter).text("command: "+$.trim($("#command").val())+"##  start time: "+ first_time.toLocaleTimeString()+"##  end time: "+endDate.toLocaleTimeString());
                    $('#one_by_one_result').html(result_string)
                    $('#one_by_one_title').text("Result is below:")
                    if (counter == 1){
                        $("#panel-body"+total_panel_counter).html(result_string)
                    }
                    else{
                        $("#panel-body"+total_panel_counter).html($("#panel-body"+total_panel_counter).html().concat(result_string))
                    }
                    if (counter>=post_hostid.length){
                        $('#next_host').text("Done");
                    }
                    }
                    }
            )
        }

        function post_all_to_server(){
            var startDate= new Date()
            var datestring=startDate.getTime().toString()
            command_token=datestring.concat('_',s10())
            var total_panel_counter = 1
            check_number=/^\d+$/;
            timeout=$.trim($("#timeout").val())
            if(!check_number.test(timeout)){
                alert("timeout must be a number")
                return false
            }
            if($.trim($("#command").val())==""){
                alert("please give me the command!")
                return false
            }
            if(post_hostid.length == 0){
                alert("please select the hosts !")
                return false
            }
            panel_count=$(".panel-default").size()
            if($.trim($("#panel-body1").text()) != "Display here.") {
                addnew_panel(panel_count);
                total_panel_counter=panel_count+1
            }
            $('#percentage_Modal').modal('show');
            $.ajax({
                        url: "/command",
                        type: 'POST',
                        data:{
                        csrf_token:"{{ csrf_token() }}",
                        runuser:$('input[name="runuser"]:checked').val(),
                        command: $.trim($("#command").val()),
                        checked_hostid:post_hostid.join(","),
                        timeout:timeout,
                        command_token:command_token
                        },
                        dataType:"html",
                        timeout:0,
                        statusCode: {
                        500: function() {
                            $('#percentage_Modal').modal('hide');
                        alert( "Sorry , something is wrong with octopus" );
                        },
                        400: function() {
                            $('#percentage_Modal').modal('hide');
                        alert( "Sorry , CSRF token expired or missing,please refresh this page" );
                        }
                        },
//                        error:function(jqXHR,textStatus,errorThrown){
//                            $('#percentage_Modal').modal('hide');
//                            alert(errorThrown);
//                        },
                        success:function(data,status){
                        content=data;
                        var endDate=new Date();
                        tmp_json=JSON.parse(content)
                        result_string=""
                        for (var i=0;i< tmp_json.length;i++){
                        result_string=result_string+tmp_json[i][0]+"</br>"+tmp_json[i][1]+"<br>"
                        result_string=result_string.replace(/\r\n/g,"<br>")
                        }
                    $('#percentage_Modal').modal('hide');
                    $("#panel-title"+total_panel_counter).text("command: "+$.trim($("#command").val())+"##  start time: "+ startDate.toLocaleTimeString()+"##  end time: "+endDate.toLocaleTimeString());
                    $("#panel-body"+total_panel_counter).html(result_string);
                    }
                    }
            )
                    $('#finished_count').css("width","1%");
                    $('#display_count').text("1% Complete");
        }
	</SCRIPT>

    <h1>Run a command</h1>

    <div class="container">
    <div class="myleft">
        <table class="above-ztree">
            <tr><th>select hosts</th></tr></table>
        <ul id="hosttree" class="ztree"></ul>
    </div>
    <div class="myright">


						You have selected <span id="checked_hosts_count"></span> hosts, here is your selection:  <span id="checked_hosts" ></span>

        </br>
        </br>

        <div class="alert alert-warning alert-dismissable">
  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
  <strong>Warning!</strong> If your command runs more than 60 seconds ,you need increase the timeout below !
</div>

        <form role="form" class="form-group" method="post" action="/command" >
                {{ form.csrf_token }}
            <div class="radio-inline">
            <label>
            <input type="radio" name="runuser" id="optionsRadios1" value="non-root" checked>
               run as non-privileged user
            </label>
            </div>
            <div class="radio-inline">
            <label>
            <input type="radio" name="runuser" id="optionsRadios2" value="root">
              run as root
            </label>
            </div>
             <div class="input-group">
            <span class="input-group-addon">*  Command</span>
            {{form.command(class="form-control",placeholder="command you want to run")}}
              </div>
            </br>
             <div class="input-group">
            <span class="input-group-addon">  Timeout (seconds)</span>
            {{form.timeout(class="form-control")}}
              </div>
            </br>
            <button type="button" class="btn btn-primary" onclick="post_all_to_server()">Run Parallel !</button>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <button type="button" class="btn btn-primary" onclick="post_one_to_server()">Run One by One !</button>
            </form>



    </div>
        <div class="clear"></div>

    <div class="panel-group" id="accordion">
  <div class="panel panel-default" id="panel1">
    <div class="panel-heading">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-toggle="collapse" data-parent="#accordion" href="#collapse1" id="panel-title1">
          Command Result will display below:
        </a>
      </h4>
    </div>
    <div id="collapse1" class="panel-collapse collapse in">
      <div class="panel-body" id="panel-body1">
       Display here.
      </div>
    </div>
  </div>




</div>


 <div class="modal fade" id="percentage_Modal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Please wait....</h4>
      </div>
      <div class="modal-body">
        <div class="progress progress-striped active">
            <div id="finished_count" class="progress-bar"  role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 1%">
            <!--<span class="sr-only">45% Complete</span>-->
             <span id="display_count">45% Complete</span>
            </div>
        </div>
      <span id="display_count_text"></span>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div>

 <div class="modal fade" id="one_by_one">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="one_by_one_title" >Please wait....</h4>
      </div>
      <div class="modal-body" id="one_by_one_result">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="post_one_to_server()" id="next_host">Next host</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div>


</div>



{% endblock %}
